﻿using Google.Ads.GoogleAds.Config;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Ads.GoogleAds.V18.Errors;
using Google.Ads.GoogleAds.V18.Services;

namespace ConsoleApp1
{
    public class GoogleGetData
    {
        public GoogleGetData()
        {
            // 步骤 1: 获取 refresh_token
            string refreshToken1 = GetRefreshToken(
                clientId: "55197948878-ciegvfefrpiotora0b0d1riarlk1cvp6.apps.googleusercontent.com",
                clientSecret: "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");

            // 步骤 2: 使用 refresh_token 调用 Google Ads API
            string refreshToken = "1//0ePuXI58w1gSVCgYIARAAGA4SNwF-L9IrCziw3OsnG0vhbpxvkWVCy4OQDvSA6pUx0yb-wz0ePqsubLxBuhTCplL7u9xGHA0ewJE";
            ListCampaigns(
                developerToken: "6x5YvfqViYnxPAmZ4ypBwg",
                clientId: "55197948878-ciegvfefrpiotora0b0d1riarlk1cvp6.apps.googleusercontent.com",
                clientSecret: "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",
                refreshToken: refreshToken,
                customerId: "9703792598");

        }
        /// <summary>
        /// 获取 refresh_token
        /// </summary>
        static string GetRefreshToken(string clientId, string clientSecret)
        {
            string[] scopes = new string[] { "https://www.googleapis.com/auth/adwords" };

            // 创建 OAuth2 客户端凭据
            var clientSecrets = new ClientSecrets
            {
                ClientId = clientId,
                ClientSecret = clientSecret,
            };

            var flow = new GoogleAuthorizationCodeFlow(
                new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = clientSecrets,
                    Scopes = scopes,
                    //IncludeGrantedScopes=true,
                    Prompt = "consent"
                });

            // 获取授权 URL
            //var authUrl = flow.CreateAuthorizationCodeRequest("urn:ietf:wg:oauth:2.0:oob").Build();
            var authUrl = flow.CreateAuthorizationCodeRequest("https://www.googleapis.com/auth/adwords").Build();
            Console.WriteLine("请访问以下 URL 以授权应用程序访问您的 Google Ads 帐号:");
            Console.WriteLine(authUrl);

            // 尝试在默认浏览器中打开授权 URL
            try
            {
                Process.Start(new ProcessStartInfo
                {
                    FileName = authUrl.ToString(),
                    UseShellExecute = true
                });
            }
            catch (Exception)
            {
                Console.WriteLine("无法自动打开浏览器，请手动复制 URL 到浏览器中访问。");
            }


            Console.Write("请输入授权码: ");
            string authorizationCode = Console.ReadLine();
            //string authorizationCode = "1//05k1wodJ52nh9CgYIARAAGAUSNwF-L9IrZagCCd_R8rmRUw9sijnlZLVkEpr5p1_e5m3rleuUiPRXFAB4aN3xTNwOJKw6kWH-HHY";
            // 通过授权码兑换 Token
            //var token = flow.ExchangeCodeForTokenAsync(
            //    "user",
            //    authorizationCode,
            //    "urn:ietf:wg:oauth:2.0:oob",
            //    System.Threading.CancellationToken.None).Result;
            var token = flow.ExchangeCodeForTokenAsync(
                "user",
                authorizationCode,
                "https://www.googleapis.com/auth/adwords",
                System.Threading.CancellationToken.None).Result;
            Console.WriteLine($"获取的 Refresh Token 是: {token.RefreshToken}");
            return token.RefreshToken;
        }

        /// <summary>
        /// 使用 refresh_token 调用 Google Ads API 列出广告系列
        /// </summary>
        static void ListCampaigns(
            string developerToken,
            string clientId,
            string clientSecret,
            string refreshToken,
            string customerId)
        {
            // 初始化 Google Ads 客户端配置
            GoogleAdsConfig config = new GoogleAdsConfig
            {
                //OAuth2Mode = Google.Ads.Gax.Config.OAuth2Flow.APPLICATION,
                DeveloperToken = developerToken,
                OAuth2ClientId = clientId,
                OAuth2ClientSecret = clientSecret,
                OAuth2RefreshToken = refreshToken,
                LoginCustomerId = customerId
            };
            //GoogleAdsConfig config = new GoogleAdsConfig
            //{
            //    DeveloperToken = "developerToken",
            //    OAuth2Mode = Google.Ads.Gax.Config.OAuth2Flow.SERVICE_ACCOUNT,
            //    OAuth2SecretsJsonPath = "D:\\OtherSystem\\InterfaceManage\\Colder.Admin.AntdVue-master\\ConsoleApp1\\credentials.json",
            //    LoginCustomerId = customerId
            //};
            // 创建 Google Ads 客户端
            GoogleAdsClient client = new GoogleAdsClient(config);

            // 获取 Google Ads 服务
            //Google.Ads.GoogleAds.V18.Services.
            GoogleAdsServiceClient service = client.GetService(Services.V18.GoogleAdsService);

            // 查询广告系列
            string query = @"SELECT
                    campaign.id,
                    campaign.name,
                    campaign.network_settings.target_content_network
                FROM campaign
                ORDER BY campaign.id";

            Console.WriteLine("广告系列列表:");

            try
            {

                //List items = new List();
                //service.SearchStream(customerId.ToString(), query,
                //    delegate (SearchGoogleAdsStreamResponse resp)
                //    {
                //        foreach (GoogleAdsRow googleAdsRow in resp.Results)
                //        {
                //            //ListViewItem item = new ListViewItem();
                //            Console.WriteLine($"ID: {googleAdsRow.Campaign.Id}, Name: {googleAdsRow.Campaign.Name}, Status: {googleAdsRow.Campaign.Status}");
                //            //item.SubItems.Add(googleAdsRow.Campaign.Name);
                //            //items.Add(item);
                //        }
                //    }
                //);

                // 执行查询
                var response = service.Search(customerId, query);
                var C = response.Count();
                // 输出结果
                foreach (var row in response)
                {
                    Console.WriteLine($"ID: {row.Campaign.Id}, Name: {row.Campaign.Name}, Status: {row.Campaign.Status}");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine($"调用 Google Ads API 时出错: {e.Message}");
                Console.WriteLine($"调用 Google Ads API 时出错: Failure: {e.Failure}");
                Console.WriteLine($"调用 Google Ads API 时出错: Request ID: {e.RequestId}");
            }
        }

    }
}
